package br.org.acessobrasil.portal.persistencia;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import br.org.acessobrasil.portal.modelo.ArquivoLog;
import br.org.acessobrasil.portal.modelo.Usuario;
import br.org.acessobrasil.portal.util.MySqlConnection;

@Transactional
public class LogDao {
	private static LogDao instance;
	private static Logger logger = Logger.getLogger(LogDao.class);
	HttpServletRequest request;
	public LogDao(){
		instance = this;
	}
	private EntityManager entityManager;
	
	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.entityManager = em;
	}

	/**
	 * Apaga at&eacute; um m&ecirc;s da data atual
	 */
	public void apagar(){
		Query query = getEntityManager().createQuery("Delete From ArquivoLog where data < ?");
		Date dataDeUmMes =  new Date();
		dataDeUmMes.setTime(dataDeUmMes.getTime()-30*24*60*60*1000L);
		query.setParameter(1,dataDeUmMes);
		query.executeUpdate();
	}
	private EntityManager getEntityManager() {
		return entityManager;
	}
	private void adicionaLog(ArquivoLog log) throws SQLException {
		try{
			getEntityManager().persist(log);
		}catch(Exception e){
			logger.error("Erro ao gravar log ",e);
		}
	}
   // precisa passar apenas a mensagem para inserir do banco
	public void addLog(Usuario usuario,String msg)/* throws SQLException*/ {
		try {
			ArquivoLog log=arrumarLog(usuario,msg);
			adicionaLog(log);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	@SuppressWarnings("unchecked")
	public List<ArquivoLog> listar(){
		return getEntityManager().createQuery("Select a From ArquivoLog a order by data desc").getResultList();
	}
	public static LogDao getInstance() {
		return instance;
	}
	
	private ArquivoLog arrumarLog(Usuario usuario,String msg) {
		// Insere o log no banco.
		ArquivoLog logg = new ArquivoLog();
		if(usuario!=null){
			logg.setNuUsuario(usuario.getNuUsuario());
		}
		logg.setMensagem(msg);
		logg.setData(new Date());
		return logg;
	}
	
	@SuppressWarnings("unchecked")
	public List<ArquivoLog> procurar(String logMensagem, Date dt_inicio, Date dt_fim) {
		Query q = getEntityManager().createQuery("Select l From ArquivoLog l where l.mensagem like ? and ? <= l.data and l.data <= ? order by data desc");
		q.setParameter(1, "%"+logMensagem+"%");
		q.setParameter(2, dt_inicio);
		q.setParameter(3, dt_fim);
		return q.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<ArquivoLog> procurar(String no_usuario, String logMensagem, Date dt_inicio, Date dt_fim) {
		Query q = getEntityManager().createQuery("Select l From ArquivoLog l where (l.usuario.no_usuario like ? or l.usuario.co_usuario like ?) and l.mensagem like ? and ? <= l.data and l.data <= ? order by l.data desc");
		q.setParameter(1, "%"+no_usuario+"%");
		q.setParameter(2, "%"+no_usuario+"%");
		q.setParameter(3, "%"+logMensagem+"%");
		q.setParameter(4, dt_inicio);
		q.setParameter(5, dt_fim);
		return q.getResultList();
	}

}
